<template>
	<view>
		<top-navbar title="设置转赠"></top-navbar>
		<view class="header_tips acea-row">
			<view class="title">通知:</view>
			<view class="acea-row row-column">
				<text>月配为配送订单可以按次转赠给好友</text>
				<text>对方仅需要完善地址及收花日期即可领取</text>
			</view>
		</view>
		<view class="middle_area padding20">
			<view class="padding20">请选择转赠哪次:</view>
			<distribution :list="list" @itemClick="itemClick" :showTips="false" :isSelect="true"></distribution>
			<view class="btn acea-row row-center row-middle" @click="transfer">转赠给微信好友</view>
			<view class="rules padding30">
				<view class="rules_title acea-row row-center">
					<text class="txt">转赠规则</text>
					<text class="line"></text>
				</view>
				<view class="rules_item acea-row row-column">
					<text>1. 适用于所有鲜花包月套餐</text>
					<text>2. 只能转赠已生成的未开始配送的订单</text>
					<text>3. 对方可选择周六或周一收花，实际收花日期以对方领取后提示为准</text>
					<text>4. 已转出的订单不允许退款</text>
				</view>
			</view>
		</view>
		<!-- 转赠 -->
		<wyb-popup ref="popup1" type="bottom" radius="6" :showCloseIcon="false">
		    <view class="popup-content">
		        <view class="title acea-row row-center row-middle">
					<text class="iconfont icon-guanbi" @click='$refs.popup1.hide()'></text>
				</view>
				<view class="pop-body acea-row row-column row-center row-middle">
					<text>确定分享一个配送单吗？</text>
				</view>
				<view class="foot acea-row row-center row-middle">
					<view class="cancelbnt" @click="$refs.popup1.hide()">取消</view>
					<view class="bnt bg-green" @click="confirm">确定</view>
				</view>
		    </view>
		</wyb-popup>
		
		<view class="poster-pop" v-if="posterImageStatus">
			<!-- #ifdef H5 -->
			<img :src="posterImage" mode="widthFix"></img>
			<!-- #endif -->
			<!-- #ifdef MP -->
			<image :src="posterImage" mode="widthFix" @longpress="longpress"></image>
			<!-- #endif -->
			<view class="close" @click="posterImageClose"></view>
		</view>
		<canvas class="canvas" canvas-id="myCanvas" v-if="canvasStatus"></canvas>
		<view class="mask" v-if="posterImageStatus"></view>
	</view>
</template>

<script>
	import {
		orderCanTransfer,
		orderTransfer
	} from '@/api/order.js';
	import { HTTP_REQUEST_URL } from '@/config/app.js';
	export default {
		data() {
			return {
				list: [],
				selectList: [],
				orderId: '',// 主订单id
				posterImage: '',
				canvasStatus: false, //海报绘图标签
				posterImageStatus: false,
			};
		},
		onLoad(opt) {
			if(opt.list) {
				let data = JSON.parse(opt.list)
				this.list = data
			}
			if(opt.orderId) {
				this.orderId = opt.orderId
				this.getCanTransfer(opt.orderId)
			}
		},
		methods: {
			// 获取月配订单可转赠的子订单
			getCanTransfer(id) {
				orderCanTransfer({order_id: id}).then(res => {
					res.data.map(el => {
						el.checked = false
					})
					this.list = res.data
				})
			},
			itemClick(e, index) {
				if(e.is_transfer == 1) {
					return this.$util.Tips({
						title: '请选择未赠送的订单'
					});
				}
				if(e.checked) {
					this.selectList.push(e.id)
					this.$set(this.list[index], 'checked', true)
				} else {
					let key = this.selectList.findIndex(el => el == e.id)
					this.selectList.splice(key, 1)
					this.$set(this.list[index], 'checked', false)
				}
			},
			transfer() {
				if(this.selectList.length == 0) {
					return this.$util.Tips({
						title: '请选择转赠哪次'
					});
				}
				this.$refs.popup1.show()
			},
			async confirm() {
				let that = this
				this.$refs.popup1.hide()
				uni.showLoading({
					title: '海报生成中...'
				})
				that.$set(that, 'canvasStatus', true);
				orderTransfer({
					shippingIds: this.selectList.toString(), // 选择转赠的订单id，多个逗号分隔
					orderId: this.orderId, // 主订单id
					re: 0
				}).then(async res => {
					if(res.status == 200) {
						let Img, arr2;
						if(HTTP_REQUEST_URL == 'https://flohy.ming.net.cn') {
							Img = 'https://flohy.ming.net.cn/uploads/attach/2021/12/20211214/bd207800eeb78577ab127776c200bcd9.png';
						} else {
							Img = 'https://pro.ming.net.cn/uploads/attach/2021/12/20211211/389d67fd53b438b66af62351783ae95a.png';
						}
						let qrCode = res.data.code;
						// #ifdef H5
						arr2 = [
							qrCode, 
							await this.downloadFilestoreImage(Img)
						];
						// #endif
						// #ifdef MP
						arr2 = [
							await this.base64ToSave(qrCode), 
							await this.downloadFilestoreImage(Img)
						];
						// #endif
						this.$util.orderPosterCanvas(arr2, (tempFilePath) => {
							that.$set(that, 'posterImage', tempFilePath);
							that.$set(that, 'posterImageStatus', true);
							that.$set(that, 'canvasStatus', false);
							// #ifdef MP
							that.removeSave()
							// #endif
							uni.hideLoading();
						});
						this.selectList = []
					} else {
						uni.hideLoading();
						this.$util.Tips({
							title: res.msg
						});
					}
				})
			},
			//隐藏海报
			posterImageClose: function() {
				this.posterImageStatus = false;
				this.getCanTransfer(this.orderId)
			},
			//图片转符合安全域名路径
			downloadFilestoreImage(url) {
				return new Promise((resolve, reject) => {
					let that = this;
					uni.downloadFile({
						url: url,
						success: function(res) {
							resolve(res.tempFilePath);
						},
						fail: function(err) {
							console.log(err)
							return that.$util.Tips({
								title: '二维码加载失败'
							});
						}
					});
				})
			},
			base64ToSave (base64data,FILE_BASE_NAME) {
				FILE_BASE_NAME = 'tmp_base64src' + Math.random(0, 10000000000)
				const fsm = uni.getFileSystemManager();
				return new Promise((resolve, reject) => {
				//format这个跟base64数据的开头对应
					const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
					if (!format) {
						reject(new Error('ERROR_BASE64SRC_PARSE'));
					}
					const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
					console.log(filePath)
					const buffer = wx.base64ToArrayBuffer(bodyData);
					fsm.writeFile({
						filePath,
						data: buffer,
						encoding: 'binary',
						success() {
							resolve(filePath);
						},
						fail() {
							reject(new Error('ERROR_BASE64SRC_WRITE'));
						},
					});
				});
			},
			removeSave(FILE_BASE_NAME='tmp_base64src',format='jpg') {
				return new Promise((resolve)=>{
					// 把文件删除后再写进，防止超过最大范围而无法写入
					const fsm = uni.getFileSystemManager();  //文件管理器
					const FILE_BASE_NAME = 'tmp_base64src';
					const format = 'jpg';
					const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
					fsm.unlink({
						filePath: filePath,
						success(res) {
							console.log('文件删除成功');
						},
						fail(e){
							console.log('readdir文件删除失败：',e)
						}
					});
				})
			
			},
			// 长按保存
			longpress() {
				let that = this;
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success() {
									uni.saveImageToPhotosAlbum({
										filePath: that.posterImage,
										success: function(res) {
											that.posterImageClose();
											that.$util.Tips({
												title: '保存成功',
												icon: 'success'
											});
										},
										fail: function(res) {
											that.$util.Tips({
												title: '保存失败'
											});
										}
									});
								}
							});
						} else {
							uni.saveImageToPhotosAlbum({
								filePath: that.posterImage,
								success: function(res) {
									that.posterImageClose();
									that.$util.Tips({
										title: '保存成功',
										icon: 'success'
									});
								},
								fail: function(res) {
									that.$util.Tips({
										title: '保存失败'
									});
								}
							});
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss">
.header_tips {
	width: 100%;
	padding: 30rpx 50rpx 10rpx;
	font-size: 30rpx;
	background-color: #fff;
	.title {
		margin-right: 20rpx;
	}
	text {
		color: #999;
		margin-bottom: 10rpx;
	}
}
.middle_area {
	background-color: #fff;
	margin-top: 20rpx;
	.btn {
		width: 400rpx;
		height: 90rpx;
		background-color: #a9d54f;
		color: #fff;
		border-radius: 50rpx;
		margin: 100rpx auto;
	}
	.rules {
		width: 100%;
		padding-bottom: 100rpx;
		.rules_title {
			position: relative;
			width: 100%;
			margin: 0 0 50rpx;
			.txt {
				position: relative;
				display: block;
				width: 200rpx;
				text-align: center;
				background-color: #fff;
				z-index: 11;
				font-size: 30rpx;
			}
			.line {
				position: absolute;
				top: 50%;
				display: block;
				width: 100%;
				height: 1px;
				background-color: #ddd;
			}
		}
		.rules_item {
			line-height: 50rpx;
			text {
				// margin-bottom: 10rpx;
				color: #666;
			}
		}
	}
}
.popup-content {
	position: relative;
	width: 100%;
	height: 100%;
	.title {
		position: relative;
		width: 100%;
		height: 100rpx;
		border-radius: 20rpx 20rpx 0 0;
		font-size: 32rpx;
		font-weight: 700;
		.iconfont {
			position: absolute;
			top: 50%;
			right: 30rpx;
			transform: translate(0,-50%) scale(0.8);
			background-color: #333;
			color: #fff;
			border-radius: 50%;
			padding: 10rpx;
			font-size: 20rpx;
		}
	}
	.close {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translate(-50%);
		z-index: 99;
		width: 100rpx;
		height: 100rpx;
	}
	.pop-body {
		padding: 0 0 30rpx;
		text {
			font-size: 32rpx;
			margin: 10rpx 0;
		}
		.option {
			width: 100%;
			height: 165rpx;
			border: 1px solid #ddd;
			border-radius: 10rpx;
		}
	}
	.foot {
		width: 100%;
		height: 120rpx;
		font-size: 30rpx;
		.cancelbnt {
			width: 230rpx;
			height: 70rpx;
			line-height: 70rpx;
			text-align: center;
			border-radius: 40rpx;
			border: 1px solid #ccc;
			margin-right: 20rpx;
		}
		.bnt {
			width: 230rpx;
			height: 70rpx;
			line-height: 70rpx;
			text-align: center;
			border-radius: 40rpx;
			border: 1px solid #a0cd43;
			color: #fff;
			margin-left: 20rpx;
		}
	}
}
.canvas {
	position: absolute;
	bottom: 100%;
	width: 505px;
	height: 759px;
}
.poster-pop {
	width: 505rpx;
	height: 759rpx;
	position: fixed;
	left: 50%;
	z-index: 399;
	top: 45%;
	// margin-top: -357rpx;
	transform: translate(-50%, -50%);
	animation: centerToHeight 0.25s linear;
	.close {
		position: absolute;
		bottom: -120rpx;
		left: 50%;
		transform: translate(-50%);
		z-index: 99;
		width: 100rpx;
		height: 100rpx;
		background: url('/static/images/poster_close.png') no-repeat center;
		background-size: 70%;
	}
}
@keyframes centerToHeight {
	0% {transform: translate(-50%, 100%);}
	100%{transform: translate(-50%, -50%);}
}
.poster-pop img,
.poster-pop image {
	width: 100%;
	height: 100%;
	display: block;
}
.mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.6);
	z-index: 300;
	animation: centerToHeight1 0.25s linear;
}
@keyframes centerToHeight1 {
	from {opacity: 0;}
	to {opacity: .6;}
}
</style>
